<template>
  <span>
    <template v-if="readonly">
      <template v-for="tag in value_display" :key="tag.id">
        <a-tag>{{ tag.display_name }}</a-tag>
      </template>
    </template>

    <template v-else>
      <OInputM2mTags
        v-model="value2"
        :options="options"
        :placeholder="node.placeholder || node.string"
        @dropdownVisibleChange="dropdownVisibleChange"
        @change="onChange"
        @search="handleSearch"
        @search-more="searchMore"
      />

      <a-form-item-rest>
        <a-modal
          v-model:open="moreOpen"
          title="搜索"
          width="600px"
          @ok="onMoreSubmit"
        >
          <div>选择: {{ moreCurrent.display_name }}</div>
          <a-table
            :dataSource="moreRecords"
            :columns="moreColumns"
            :customRow="moreTableCustomRow"
            style="margin-top: 5px"
          >
          </a-table>
        </a-modal>
      </a-form-item-rest>
    </template>
  </span>
</template>

<script setup>
import api from '@/odoojs/index.js'

import OInputM2mTags from '../OInput/OInputM2mTags.vue'

import { computed, ref } from 'vue'
import { useWidget } from './userWidget'

const props = defineProps(['modelValue', 'node', 'formInfo'])
const emit = defineEmits(['update:modelValue', 'change'])

const useData = useWidget(props, { emit })

const { readonly } = useData
const { onChange } = useData

const value2 = computed({
  get() {
    return props.modelValue || []
  },
  set(value) {
    emit('update:modelValue', value)
  }
})

const value_display = computed(() => {
  const fname = props.node.name
  const { record = {} } = props.formInfo || {}
  const val = record[fname]
  return val
})

const optionsRaw = ref([])

const options = computed(() => {
  const ops = optionsRaw.value

  const myvalue = value2.value.map(item => [item.id, item.display_name])
  // console.log(myvalue)

  return removeDuplication([...myvalue, ...ops])
})

async function dropdownVisibleChange() {
  // console.log('dropdownVisibleChange:')
  const limit = value2.value.length + 8
  const ops = await call_loadSelectOptions({ limit })

  optionsRaw.value = ops
}

async function handleSearch(val) {
  // console.log('handleSearch:', val)

  const limit = value2.value.length + 8
  const ops = await call_loadSelectOptions({ name: val, limit })

  optionsRaw.value = ops
}

async function searchMore() {
  // console.log('searchMore')
  moreLoadData()
  moreOpen.value = true
}

const moreRecords = ref([])
const moreColumns = ref([
  {
    dataIndex: 'display_name',
    key: 'display_name',
    title: '名称'
    // align: 'center'
  }
])

const moreCurrent = ref({})
const moreOpen = ref(false)

async function moreLoadData() {
  const ops = await call_loadSelectOptions({ limit: 0 })

  moreRecords.value = ops.map(item => {
    return { id: item[0], display_name: item[1] }
  })
}

function moreTableCustomRow(record) {
  return {
    // eslint-disable-next-line no-unused-vars
    onClick: event => {
      // console.log('click row ', record)
      moreCurrent.value = record
    }
  }
}

const onMoreSubmit = () => {
  const record = moreCurrent.value
  moreCurrent.value = {}
  moreOpen.value = false

  if (record.id) {
    const myvalue = value2.value.map(item => [item.id, item.display_name])
    const res = removeDuplication([
      ...myvalue,
      [record.id, record.display_name]
    ])

    const res2 = res.map(item => {
      return { id: item[0], display_name: item[1] }
    })

    value2.value = res2
    // console.log(res, value2.value)

    onChange(res2)
  }
}
async function call_loadSelectOptions(kw = {}) {
  const { record = {} } = props.formInfo || {}
  const { meta, domain = [] } = props.node
  const rel = api.env.relation({ ...meta, domain })
  return rel.load_select_options({ record, ...kw })
}

function removeDuplication(list) {
  return list.reduce((acc, cur) => {
    if (!acc.map(item => item[0]).includes(cur[0])) {
      acc.push([...cur])
    }
    return acc
  }, [])
}
</script>

<style type="text/css"></style>
